package com.kylinhunter.ch.plugin.knowledgebase.service.imp;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;

import com.khplatformtool.service.page.KHPPageTools;
import com.kylinhunter.ch.language.ResourceManager;
import com.kylinhunter.ch.plugin.knowledgebase.dao.Chcode;
import com.kylinhunter.ch.plugin.knowledgebase.dao.Chkbfile;
import com.kylinhunter.ch.plugin.knowledgebase.service.KBService;
import com.kylinhunter.ch.plugin.knowledgebase.service.Service;
import com.kylinhunter.ch.plugin.knowledgebase.ui.KownledgeBasePlugin;
import com.kylinhunter.exception.KHException;
import com.kylinhunter.exception.KHExceptionC;
import com.kylinhunter.ui.common.plugin.Plugin;
@Transactional(rollbackFor=KHException.class)
public class KBServiceImp extends BaseService implements KBService{

    private String fileDuplicate=""; 
    private String directoryDuplicate=""; 
    private String addFileError=""; 
    private String delFileError=""; 
    private String delDirectoryError=""; 
	private static final Log log = LogFactory.getLog(KBServiceImp.class);
	@Override
	public void addDirectory(Chcode directory) throws KHException {
		// TODO Auto-generated method stub	 

		Chcode directory_q=new Chcode();
		directory_q.setCodefather(directory.getCodefather());
		directory_q.setCodename(directory.getCodename());
		List<Chcode>  directorys=this.chcodeDAO.findByExample(directory_q);
		
		if(directorys.size()>=1){
			throw new KHException(KHExceptionC.ERROR,"",this.getClass().getSimpleName(),fileDuplicate);
			
		}



		chcodeDAO.save(directory);

	}

	@Override
	public void delDirectory(Chcode chcode) throws KHException {
		// TODO Auto-generated method stub
		Chcode directory=chcodeDAO.findById(chcode.getId());
		File dir=this.getDirectoryByID(directory.getId());
		Set<File> files_real=new HashSet<File> ();
		Set<Chkbfile> files=directory.getChkbfiles();
		for(Chkbfile file:files){
			File file_real=this.getFileByFileID(file.getId());
			files_real.add(file_real);
		}		
		chcodeDAO.delete(directory);
		
		for(File tem_file:files_real){
			if(tem_file.exists()){
				if(!tem_file.delete()){					 
				  throw new KHException(KHExceptionC.ERROR,"",this.getClass().getSimpleName(),this.delFileError);	
				 }
			}
			
			 
		}
		if(dir!=null){
			if(dir.exists()){
				if(!dir.delete()){
					 
					throw new KHException(KHExceptionC.ERROR,"",this.getClass().getSimpleName(),this.delDirectoryError);
				}
			}
			
		}
		
		
		
	}

	@Override
	public void modifyFileType(Chcode chcode) throws KHException {
		// TODO Auto-generated method stub
		chcodeDAO.attachDirty(chcode);
	}

	@Override
	public Chcode getDirectory(String directory) throws KHException {
		// TODO Auto-generated method stub
		return   chcodeDAO.findById(directory);

	}

	@Override
	public List<Chcode> getDirectoryByExample(Chcode directory) throws KHException {
		// TODO Auto-generated method stub
		if(directory==null)
			return chcodeDAO.findAll();
		else
			return  chcodeDAO.findByExample(directory);
	}

	@Override
	public List<Chcode> findAllFileTypeByPage(int pageNo, int userPageSize, boolean paging,Chcode chcode,String orderString,boolean vague)throws KHException {
		// TODO Auto-generated method stub
		int count=0;//chcodeDAO.getCount(chcode,vague);
		if(paging){
			if (pageNo < 1) {
				pageNo=1;
			}
			if(userPageSize<=0)userPageSize=Service.pageSize;


			int pagecount=KHPPageTools.getPageCount(count,  userPageSize);
			if(pageNo>pagecount){
				pageNo=pagecount;
			}
		}else{
			pageNo=1;
			userPageSize=count;
		}






		//		return chcodeDAO.findAllByPage(pageNo, userPageSize, chcode,orderString,vague);
		return null;
	}





	@Override
	public void addFile(Chkbfile chkbfile,String direcotry) throws KHException {
		// TODO Auto-generated method stub	 
		try {
			Chcode directory=this.chcodeDAO.findById(direcotry);
			chkbfile.setChcode(directory);
			chkbfileDAO.save(chkbfile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new KHException(KHExceptionC.ERROR,"",this.getClass().getSimpleName(),addFileError);
		}


	}

	@Override
	public void delFile(Chkbfile chkbfile) throws KHException {
		// TODO Auto-generated method stub
		File file=this.getFileByFileID(chkbfile.getId());
		chkbfileDAO.delete(chkbfileDAO.findById(chkbfile.getId()));
		if(file.exists()){

			boolean ok=file.delete();
			if(!ok){
				throw new KHException(KHExceptionC.ERROR,"",this.getClass().getSimpleName(),this.delFileError);
			}	
		}
	}

	@Override
	public void modifyFile(Chkbfile chkbfile) throws KHException {
		// TODO Auto-generated method stub
		chkbfileDAO.attachDirty(chkbfile);
	}

	@Override
	public Chkbfile viewFile(Chkbfile chkbfile) throws KHException {
		// TODO Auto-generated method stub
		return  chkbfileDAO.findById(chkbfile.getId());



	}

	@Override
	public List viewALLFile(Chkbfile chkbfile) throws KHException {
		// TODO Auto-generated method stub

		if(chkbfile==null)
			return chkbfileDAO.findAll();
		else
			return  chkbfileDAO.findByExample(chkbfile);
	}

	@Override
	public List<Chkbfile> findAllFileByPage(int pageNo, int userPageSize, boolean paging,Chkbfile chkbfile,String orderString,boolean vague)throws KHException {
		// TODO Auto-generated method stub
		int count=0;//chcodeDAO.getCount(chkbfile,vague);
		if(paging){
			if (pageNo < 1) {
				pageNo=1;
			}
			if(userPageSize<=0)userPageSize=Service.pageSize;


			int pagecount=KHPPageTools.getPageCount(count,  userPageSize);
			if(pageNo>pagecount){
				pageNo=pagecount;
			}
		}else{
			pageNo=1;
			userPageSize=count;
		}






		//		return chkbfileDAO.findAllByPage(pageNo, userPageSize, chkbfile,orderString,vague);
		return null;
	}

	@Override
	public Set<Chkbfile> getAllFileByDirectory(Chcode directory) throws KHException {
		// TODO Auto-generated method stub
		Chcode q_chcode=this.chcodeDAO.findById(directory.getId());
		if(q_chcode!=null){
			Set<Chkbfile> chkbfiles=q_chcode.getChkbfiles();
			chkbfiles.size();
			return chkbfiles;	
		}else{
			return new HashSet<Chkbfile>();
		}

	}

	@Override
	public void addFile(Chkbfile chkbfile) throws KHException {
		// TODO Auto-generated method stub
		try {

			Set<Chkbfile> files=this.chcodeDAO.findById(chkbfile.getChcode().getId()).getChkbfiles();
			for(Chkbfile temp:files){
				if(temp.getFilename().equals(chkbfile.getFilename())){
					throw new KHException(KHExceptionC.ERROR,"",this.getClass().getSimpleName(),fileDuplicate);
				}
			}

			chkbfileDAO.save(chkbfile);
		}  catch (KHException e) {
			throw e;
		}	catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new KHException(KHExceptionC.ERROR,"",this.getClass().getSimpleName(),addFileError);
		}

	}

	@Override
	public String getFilePath(String fileID) throws KHException {
		// TODO Auto-generated method stub
		Chkbfile chkbfile =this.chkbfileDAO.findById(fileID);
		ArrayList<String> directory_nodes=new ArrayList <String>();
		String direcotry="";

		String directory_node=chkbfile.getChcode().getId();
		directory_nodes.add(directory_node);
		while(true){
			Chcode directory_temp=this.chcodeDAO.findById(directory_node);
			if(directory_temp.getCodefather().equals("-1")){
				break;
			}
			directory_node=directory_temp.getCodefather(); 
			directory_nodes.add(directory_node);
			log.debug("father path no is  "+directory_temp.getCodefather());


		}

		int size=directory_nodes.size();
		for(int i=size-1;i>=0;i--){
			direcotry+=File.separator+directory_nodes.get(i);
		}
		log.debug("the return path is "+direcotry);
		return System.getProperty("user.dir")+File.separator+"user_file"+direcotry;
	}

	@Override
	public Chkbfile getFile(String fileId) throws KHException {
		// TODO Auto-generated method stub
		Chkbfile chkbfile =this.chkbfileDAO.findById(fileId);
		return chkbfile;
	}

 

	@Override
	public void updateDirectoryName(String directoryId,String directoryName) throws KHException {
		// TODO Auto-generated method stub
		Chcode directory=this.chcodeDAO.findById(directoryId);
		Chcode directory_q=new Chcode();
		directory_q.setCodefather(directory.getCodefather());
		directory_q.setCodename(directoryName);
		List<Chcode>  directorys=this.chcodeDAO.findByExample(directory_q);
		
		if(directorys.size()>=1){
			throw new KHException(KHExceptionC.ERROR,"",this.getClass().getSimpleName(),directoryDuplicate);
			
		}
		
		
		
		directory.setCodename(directoryName);
		
		this.chcodeDAO.attachDirty(directory);

	}

	@Override
	public void updateFileName(String fileId, String fileName)
			throws KHException {
		// TODO Auto-generated method stub
		Chkbfile chkbfile=this.chkbfileDAO.findById(fileId);		 
		chkbfile.setFilename(fileName);
		this.chkbfileDAO.attachClean(chkbfile);
		
	}

	@Override
	public void updateResource(ResourceManager resourceManager) {
		// TODO Auto-generated method stub
		   this.fileDuplicate=resourceManager.getString(KownledgeBasePlugin.RESOURCE,"kbServiceImp.fileDuplicate");  
		   this.directoryDuplicate=resourceManager.getString(KownledgeBasePlugin.RESOURCE,"kbServiceImp.directoryDuplicate"); 
		   this.addFileError=resourceManager.getString(KownledgeBasePlugin.RESOURCE,"kbServiceImp.addFileError"); 
		   this.delDirectoryError=resourceManager.getString(KownledgeBasePlugin.RESOURCE,"kbServiceImp.delDirectoryError"); 
		   this.delFileError=resourceManager.getString(KownledgeBasePlugin.RESOURCE,"kbServiceImp.delFileError"); 
	}

	@Override
	public File getFileByFileID(String fileID) throws KHException {
		// TODO Auto-generated method stub
		String path=this.getFilePath(fileID);
		File file=new File(path+File.separator+fileID+".txt");
		return file;
	}

	@Override
	public File getDirectoryByID(String directoryID) throws KHException {
		// TODO Auto-generated method stub
		String path=this.getDirectoryPath(directoryID);
		File file=new File(path);
		return file;
	}

	@Override
	public String getDirectoryPath(String directoryID) throws KHException {
		// TODO Auto-generated method stub	
		ArrayList<String> directory_nodes=new ArrayList <String>();
		String direcotry="";
		String directory_node=directoryID;
		directory_nodes.add(directoryID);
		while(true){
			Chcode directory_temp=this.chcodeDAO.findById(directory_node);
			if(directory_temp.getCodefather().equals("-1")){
				break;
			}
			directory_node=directory_temp.getCodefather(); 
			directory_nodes.add(directory_node);
			log.debug("father path no is  "+directory_temp.getCodefather());


		}

		int size=directory_nodes.size();
		for(int i=size-1;i>=0;i--){
			direcotry+=File.separator+directory_nodes.get(i);
		}
		log.debug("the return path is "+direcotry);
		return System.getProperty("user.dir")+File.separator+"user_file"+direcotry;
		 
	}





}
